//
//  BAAlbumIndexManager.m
//  BabyAlbum
//
//  Created by master on 17/2/15.
//  Copyright © 2017年 master. All rights reserved.
//

#import "BAAlbumIndexManager.h"

@implementation BAAlbumIndexManager {
    NSHashTable *_delegates;
}

+ (instancetype)shareInstance {
    static BAAlbumIndexManager *handle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if(!handle) {
            handle = [[BAAlbumIndexManager alloc] init];
        }
    });
    return handle;
}

- (instancetype)init {
    if(self = [super init]) {
        _delegates = [NSHashTable hashTableWithOptions:NSPointerFunctionsWeakMemory];
        [self reloadData];
        NSLog(@"%@",_albumList);
    }
    return self;
}

- (void)setAlbumList:(NSArray *)albumList {
    if(![_albumList isEqual:albumList]) {
        _albumList = albumList;
        for (id<BAAlbumDataProtocol> delegate in _delegates) {
            if([delegate respondsToSelector:@selector(albumManagerDataSourceDidChanged:)]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [delegate albumManagerDataSourceDidChanged:self];
                });
            }
        }
    }
}

- (void)reloadData {
    self.albumList = [BADB allAlbums];
    if(self.currentIndex >= self.albumList.count) {
        self.currentIndex = self.albumList.count - 1;
    }
//    NSLog(@"%@",_albumList);

}

- (void)setDelegate:(id<BAAlbumDataProtocol>)delegate {
    if(_delegates != nil) {
        [_delegates addObject:delegate];
    }
}

- (void)removeDelegate:(id<BAAlbumDataProtocol>)delegate {
    [_delegates removeObject:delegate];
}

- (void)setCurrentIndex:(NSInteger)currentIndex {
//    NSLog(@"%@",[NSDate date]);
//    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    if(self.currentIndex != currentIndex) {
        _currentIndex = currentIndex;
        [self effectIndex];

    }
//    [self performSelector:@selector(effectIndex) withObject:nil afterDelay:2];
}

- (void)effectIndex {
    for (id<BAAlbumDataProtocol> delegate in _delegates) {
        if([delegate respondsToSelector:@selector(albumManager:didChangeToIndex:)]) {
            [delegate albumManager:self didChangeToIndex:_currentIndex];
        }
    }}

@end
